package com.softer.chengxin.project.dao.provider;

import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.common.domin.Page;
import com.softer.chengxin.project.domin.Project;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;

/**
 * @author Gong Zhiyang
 * @date 2018/10/13
 */
public class ProjectDaoProvider {
    /**
     * 查询项目信息数量
     *
     * @param map 参数
     * @return sql
     */
    public String queryNum(HashMap<String, Object> map) {
        StringBuffer sql = new StringBuffer(20);
        String states = (String) map.get("states");
        Project project = (Project) map.get("project");
        sql.append("SELECT count(*) FROM company_project WHERE company_id=#{project.companyId}");
        sql.append(" and state IN(").append(states).append(")");
        commonSql(sql, project);
        return sql.toString();
    }

    /**
     * 查询项目信息列表
     *
     * @param map 参数
     * @return sql
     */
    public String queryList(HashMap<String, Object> map) {
        StringBuffer sql = new StringBuffer(20);
        Page page = (Page) map.get("page");
        String states = (String) map.get("states");
        Project project = (Project) map.get("project");
        sql.append("SELECT id, project_name as projectName,project_id as projectId,detailed_address as detailedAddress,DATE_FORMAT(entrust_begin_time, '%Y-%m-%d') AS `entrustBeginTime` ,state");
        sql.append(" FROM company_project WHERE company_id=#{project.companyId}");
        sql.append(" and state IN(").append(states).append(")");
        commonSql(sql, project);
        sql.append(" LIMIT ");
        sql.append(page.getBeginIndex()).append(",").append(page.getLimit());
        return sql.toString();
    }

    private void commonSql(StringBuffer sql, Project project) {
        String projectId = project.getProjectId();
        if (!Common.ZERO.equals(projectId)) {
            sql.append(" and id=#{project.projectId}");
        }
        if (StringUtils.isNotBlank(project.getProjectName())) {
            sql.append(" AND INSTR(project_name,#{project.projectName})>0");
        }
        if (project.getState() != null) {
            sql.append(" AND state =#{project.state}");
        }
    }
}
